#include <stdio.h>
#include "AppDX9.h"

extern CApplication *g_pApp;

LPDIRECT3DDEVICE9 CAppDX9::GetD3DDevice()
{
    return ((CAppDX9*)g_pApp)->m_pD3DDevice;
}

CAppDX9::CAppDX9(int a_iWidth, int a_iHeight)
: CApplication(a_iWidth, a_iHeight)
{
    D3DDISPLAYMODE DisplayMode;
    D3DPRESENT_PARAMETERS DisplayParams;
    m_pD3DInterface = Direct3DCreate9( D3D_SDK_VERSION );
    m_pD3DInterface->GetAdapterDisplayMode( D3DADAPTER_DEFAULT, &DisplayMode );
    DisplayMode.Height = a_iHeight;
    DisplayMode.Width  = a_iWidth;

    ZeroMemory( &DisplayParams, sizeof(DisplayParams) );
    DisplayParams.Windowed   = TRUE;
    DisplayParams.SwapEffect = D3DSWAPEFFECT_DISCARD;
    DisplayParams.BackBufferFormat = DisplayMode.Format;
    DisplayParams.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
    m_pD3DInterface->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, 
        m_hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, 
        &DisplayParams,  &m_pD3DDevice );
    D3DXCreateFontA(m_pD3DDevice, 24, 0, FW_BOLD, 0, FALSE, DEFAULT_CHARSET, 
        OUT_DEFAULT_PRECIS, DEFAULT_QUALITY,  
        DEFAULT_PITCH, LPCSTR("Times New Roman"), &m_pFont);
}

void CAppDX9::RenderText(RECT rect, char *fmt, ...)
{
    char        text[256];                              
    va_list     ap; 
    va_start(ap, fmt);                                  
    vsprintf_s(text, 256, fmt, ap);                        
    va_end(ap);
    m_pFont->DrawTextA(NULL, text, -1, &rect, DT_LEFT, 
        D3DCOLOR_XRGB(255,255,255));
}

void CAppDX9::RenderScene()
{
    m_pD3DDevice->BeginScene();
    m_pD3DDevice->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0);
    CApplication::RenderScene( );

    RECT rcFpsText;
    DWORD elapsed = 0;
    static DWORD FpsCount = 0;
    static DWORD FrameNum = 0;
    static DWORD FpsTimeCount = 0;
    static DWORD curtime = GetTickCount();
    rcFpsText.left = 0;
    rcFpsText.top = 10;
    rcFpsText.right = 200;
    rcFpsText.bottom = 100;
    elapsed = GetTickCount() - curtime;
    FpsTimeCount += elapsed;
    FrameNum++;
    curtime = GetTickCount();
    if (FpsTimeCount > 1000)
    {
        FpsTimeCount = 0;
        FpsCount = FrameNum;
        FrameNum = 0;
    }
    RenderText(rcFpsText, "DX9 Renderer\nFps = %d", FpsCount);

    m_pD3DDevice->EndScene();
    m_pD3DDevice->Present( NULL, NULL, NULL, NULL );
}

CAppDX9::~CAppDX9()
{
    m_pD3DDevice->Release();
    m_pD3DInterface->Release();
    m_pFont->Release();
}